package com.hctforgreen.greenservice.examine;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.taptwo.android.widget.ViewFlow;
import org.taptwo.android.widget.ViewFlow.ViewSwitchListener;

import u.aly.cy;
import u.aly.da;
//import u.aly.dm;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ExamHistoryListActivity;
import com.hctforgreen.greenservice.ExamSearchActivity;
import com.hctforgreen.greenservice.MainActivityV2;
import com.hctforgreen.greenservice.ParentActivity;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbExamController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.AllExamListEntity;
import com.hctforgreen.greenservice.model.ExamPaperEntity;
import com.hctforgreen.greenservice.model.ExamPaperEntity.PAPER_TYPE;
import com.hctforgreen.greenservice.model.ExamSubEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.model.UserInfoEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.ui.adapter.ExamDetailChildListAdapter;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.UserInfoStoreUtil;

/**
 * 考试页面
 * 
 * @author Denghb
 * @time 2015-6-4
 * @version 1
 * @since V2.3.0
 */
public class CountDownExamDetailActivity extends ParentActivity {

	private ViewFlow mViewFlow = null;
	private ExamDetailChildListAdapter mAdapter = null;

	private ExamPaperEntity mPaperEntity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.count_down_exam_detail_activity);

		Intent intent = getIntent();

		mPaperEntity = (ExamPaperEntity) intent
				.getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY);

		initSkinLayout();
		initFinshExamineActivityReceiver();
		initTitleButtonBar();
		initWindowType();
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.train_examine));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showLeaveDialog();
			}
		});
		Button btnRight = (Button) findViewById(R.id.btn_right);
		btnRight.setText(getString(R.string.exam_submit));
		/**
		 * 交卷
		 */
		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mAdapter == null) {
					return;
				}
				Intent intent = new Intent(CountDownExamDetailActivity.this,
						SeeNotYetActivity.class);
				HctApplication.examSubEntities = mAdapter.getmEntities();
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY,
						mPaperEntity);
				startActivityForResult(
						intent,
						HctConstants.ON_ACTIVITY_RESULT_NOT_YET_OR_SITUATION_LIST_ACTIVITY);

				// showMakeSureDialog();
			}
		});
		// InitTitle.initTitle(this, R.drawable.btn_reback, "考试", 0,
		// new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// finish();
		// }
		//
		// }, null);
	}

	private void initWindowType() {
		loadDataLst();
	}

	private void initWindow(List<ExamSubEntity> dataLst) {
		if (dataLst == null || dataLst.size() <= 0) {
			Toast.makeText(this, getString(R.string.empty_exam_hint),
					Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		initViewFlow(dataLst);
		initBottomBarBtns();
	}

	private void loadDataLst() {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
		final Button reloadBtn = (Button) findViewById(R.id.btn_default_reload);
		final LinearLayout countLyt = (LinearLayout) findViewById(R.id.lyt_default_content);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;
					List<ExamSubEntity> data = (List<ExamSubEntity>) hctResult.data;

					initWindow(data);
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadLyt.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

						}
					});
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							loadDataLst();
						}
					});
					break;
				}

			}

		};
		loadLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		countLyt.setVisibility(View.VISIBLE);
		loadLyt.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				Message message = new Message();
				HctResult result = null;
				if (mPaperEntity.paperType == PAPER_TYPE.TYPE_CACHE) {// 草稿
					DbExamController dbExamController = new DbExamController(
							CountDownExamDetailActivity.this);
					try {
						List<ExamSubEntity> subEntities = dbExamController
								.getExamSubListByPaperId(mPaperEntity.id);
						result = new HctResult();
						result.data = subEntities;
						result.status = HctConstants.STATUS_SUCCESS;
						message.what = result.status;
						message.obj = result;
					} catch (Exception e) {
						e.printStackTrace();
						message.what = HctConstants.STATUS_FAILD;
					}

				} else {
					try {
						HctController controller = new HctController(
								CountDownExamDetailActivity.this);
						result = controller.getExamPageSub(mPaperEntity.id);
						if (result.status == HctConstants.STATUS_SUCCESS) {
							message.what = result.status;
							message.obj = result;
						} else {
							message.what = HctConstants.STATUS_FAILD;
						}
					} catch (Exception e) {
						e.printStackTrace();
						message.what = HctConstants.STATUS_FAILD;
					}
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void initBottomBarBtns() {
		/**
		 * 上一题
		 */
		final View prevBtn = findViewById(R.id.lyt_prev);
		/**
		 * 下一题
		 */
		final View nextBtn = findViewById(R.id.lyt_next);

		// if (mAdapter.getmIndex() == 0) {
		// prevBtn.setVisibility(View.GONE);
		// }
		// if (mAdapter.getmIndex() == mAdapter.getCount() - 1) {
		// nextBtn.setVisibility(View.GONE);
		// }

		prevBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mAdapter.getmIndex() != 0) {
					mViewFlow.setSelection(mAdapter.getmIndex() - 1);
				} else {
					Toast.makeText(CountDownExamDetailActivity.this,
							getString(R.string.is_always_first_item),
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		nextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mAdapter.getmIndex() < mAdapter.getCount() - 1) {
					mViewFlow.setSelection(mAdapter.getmIndex() + 1);
				} else {
					Toast.makeText(CountDownExamDetailActivity.this,
							getString(R.string.is_always_last_item),
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		/**
		 * 交卷
		 */
		Button addScoBtn = (Button) findViewById(R.id.btn_add_sco);
		addScoBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// showMakeSureDialog();

			}

		});
		/**
		 * 查看未做
		 */
		Button notYetBtn = (Button) findViewById(R.id.btn_not_yet);
		notYetBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent();
				// intent.setClass(CountDownExamDetailActivity.this,
				// SeeNotYetActivity.class);
				// AllExamListEntity listEntity = new AllExamListEntity();
				// listEntity.dataList = mAdapter.getmEntities();
				// intent.putExtra(
				// HctConstants.ON_ACTIVITY_KEY_ALL_EXAM_LIST_ENTITY,
				// listEntity);
				// startActivityForResult(
				// intent,
				// HctConstants.ON_ACTIVITY_RESULT_NOT_YET_OR_SITUATION_LIST_ACTIVITY);
			}
		});

	}

	/**
	 * 是否做完
	 * 
	 * @param entity
	 * @return
	 */
	private boolean isAlready(final ExamSubEntity entity) {
		boolean bAlready = false;
		if (!entity.inputAnswer.equals("")) {
			bAlready = true;
		}
		if ((entity.inputAnswerList != null && entity.inputAnswerList.size() > 0)) {
			for (String sInputAnswer : entity.inputAnswerList) {
				if (!sInputAnswer.equals("")) {
					bAlready = true;
				}
			}
		}
		return bAlready;
	}

	private void initViewFlow(final List<ExamSubEntity> childEntities) {
		if (mViewFlow == null) {
			mViewFlow = (ViewFlow) findViewById(R.id.viewflow);
			mViewFlow.setEnableScroll(false);
			mViewFlow.setbResetFoucusInSelection(true);
			mAdapter = new ExamDetailChildListAdapter(
					CountDownExamDetailActivity.this, mViewFlow, childEntities,
					"");

			mAdapter.setbShowAnswerLayout(false);
			int adSize = childEntities.size();
			mViewFlow.setAdapter(mAdapter);

			mViewFlow.setOnViewSwitchListener(new ViewSwitchListener() {

				@Override
				public void onSwitched(View view, int position) {

					mAdapter.setmIndex(position);
					ExamSubEntity entity = (ExamSubEntity) mAdapter
							.getItem(position);
					changeTitle(entity);
					findViewById(R.id.lyt_prev).setVisibility(View.VISIBLE);
					findViewById(R.id.lyt_next).setVisibility(View.VISIBLE);
					if (position == 0) {
						findViewById(R.id.lyt_prev).setVisibility(
								View.INVISIBLE);
					} else if (position == mAdapter.getCount() - 1) {
						findViewById(R.id.lyt_next).setVisibility(
								View.INVISIBLE);
					}
				}

				/**
				 * 标题
				 * 
				 * @param entity
				 */
				private void changeTitle(ExamSubEntity entity) {
					TextView indicTv = (TextView) findViewById(R.id.tv_title);
					if (entity.type.equals("1")) {
						indicTv.setText(getString(R.string.q_type_1_1));
					} else if (entity.type.equals("2")) {
						indicTv.setText(getString(R.string.q_type_1_2));
					} else if (entity.type.equals("3")) {
						indicTv.setText(getString(R.string.q_type_2));
					} else if (entity.type.equals("4")) {
						indicTv.setText(getString(R.string.q_type_3));
					}
				}
			});
			int startIndex = 0;
			if (adSize > startIndex) {
				mViewFlow.setSelection(startIndex);
				mAdapter.setmIndex(startIndex);
			}
		}

	}

	final Handler timeOutHandler = new Handler() {
		public void handleMessage(Message msg) {
			Toast.makeText(CountDownExamDetailActivity.this,
					getString(R.string.time_out_hint), Toast.LENGTH_SHORT)
					.show();
			// addSco();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		/**
		 * 设置的回调
		 */
		case HctConstants.ON_ACTIVITY_RESULT_NOT_YET_OR_SITUATION_LIST_ACTIVITY:
			if (resultCode == Activity.RESULT_OK) {
				Bundle bundle = data.getExtras();
				int position = bundle
						.getInt(HctConstants.ON_ACTIVITY_KEY_POSITION);
				mViewFlow.setSelection(position);
			}
			break;
		}
	}

	/**
	 * 提交试卷
	 */
	// private void addSco() {
	// try {
	//
	// final ProgressDialog progressDialog = new ProgressDialog(this);
	// progressDialog
	// .setMessage(getString(R.string.dialog_add_sco_content_hint));
	// final Handler handler = new Handler() {
	// public void handleMessage(Message msg) {
	// progressDialog.dismiss();
	// HctResult hctResult = new HctResult();
	// switch (msg.what) {
	// case HctConstants.STATUS_SUCCESS:
	// hctResult = (HctResult) msg.obj;
	// ResultEntity entity = (ResultEntity) hctResult.data;
	// if (entity.state
	// .equals(HctConstants.RESULT_STATE_SUCCESS)) {
	// Toast.makeText(CountDownExamDetailActivity.this,
	// "提交成功!", Toast.LENGTH_SHORT).show();
	// startResultsShowActivity();
	//
	// } else {
	// Toast.makeText(CountDownExamDetailActivity.this,
	// getString(R.string.net_error_hint),
	// Toast.LENGTH_SHORT).show();
	// }
	// break;
	// case HctConstants.STATUS_FAILD:
	// Toast.makeText(CountDownExamDetailActivity.this,
	// getString(R.string.net_error_hint),
	// Toast.LENGTH_SHORT).show();
	// break;
	// }
	// }
	// };
	// progressDialog.show();
	// new Thread() {
	// public void run() {
	// Message message = new Message();
	// try {
	// HctController controller = new HctController(
	// CountDownExamDetailActivity.this);
	// UserInfoEntity user = UserInfoStoreUtil
	// .getUserInfo(CountDownExamDetailActivity.this);
	// HctResult result = controller.addSco(user.userId,
	// user.userName, user.userAut, user.userDepart,
	// String.valueOf(getScore()), mPaperEntity.id,
	// getInputAnswerMsg(), "");
	// if (result.status == HctConstants.STATUS_SUCCESS) {
	// message.what = result.status;
	// message.obj = result;
	// } else {
	// message.what = HctConstants.STATUS_FAILD;
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// handler.sendMessage(message);
	// }
	// }.start();
	// } catch (Exception e2) {
	// e2.printStackTrace();
	// }
	// }

	private void startResultsShowActivity() {
		Intent intent = new Intent();
		intent.setClass(CountDownExamDetailActivity.this,
				ResultsShowActivity.class);
		// AllExamListEntity listEntity = new AllExamListEntity();
		// listEntity.dataList = mAdapter.getmEntities();
		// intent.putExtra(HctConstants.ON_ACTIVITY_KEY_ALL_EXAM_LIST_ENTITY,
		// listEntity);
		// intent.putExtra(HctConstants.ON_ACTIVITY_KEY_PAGER_ENTITY,
		// mPaperEntity);

		startActivityForResult(
				intent,
				HctConstants.ON_ACTIVITY_RESULT_NOT_YET_OR_SITUATION_LIST_ACTIVITY);
	}

	/**
	 * 获取分数
	 */
	private double getScore() {
		List<ExamSubEntity> dataList = mAdapter.getmEntities();
		/**
		 * 分数
		 */
		double iTotalScore = 0;
		for (ExamSubEntity ExamSubEntity : dataList) {
			iTotalScore += Double.valueOf(ExamSubEntity.inputAnswerScore);
		}
		return iTotalScore;
	}

	/**
	 * 拦截返回按钮
	 */
	@Override
	public void onBackPressed() {
		showLeaveDialog();
	}

	private void showLeaveDialog() {
		AlertDialog.Builder builder = new Builder(
				CountDownExamDetailActivity.this);
		final Dialog dialog = builder
				.setTitle(getString(R.string.feedback_exist_wran_title))
				.setMessage(getString(R.string.exam_leave_hint))
				.setNegativeButton(getString(R.string.feedback_exist_leave),
						new DialogInterface.OnClickListener() {// 离开

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// Intent intent = new Intent(
								// CountDownExamDetailActivity.this,
								// MainActivityV2.class);
								// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								// startActivity(intent);

								sendBroadcast(new Intent(
										ExamSearchActivity.FRESH_EXAMINE_NUM_ACTION));
								sendBroadcast(new Intent(
										FINISH_EXAMINE_ACTIVITY_ACTION));
								finish();
							}
						})
				.setPositiveButton(getString(R.string.feedback_exist_save),
						new DialogInterface.OnClickListener() {// 保存至草稿

							@Override
							public void onClick(final DialogInterface dialog,
									int which) {
								new HandlerThread("save_examPaper") {
									public void run() {
										// 插入数据库（考试草稿）
										LoginResultEntity entity = LoginResultStoreUtil
												.get(CountDownExamDetailActivity.this);
										SimpleDateFormat dateFormat = new SimpleDateFormat(
												"yyyy-MM-dd HH:mm:ss");
										mPaperEntity.createTime = dateFormat
												.format(new Date());

										mPaperEntity.personId = entity.personId;
										List<ExamSubEntity> entities = mAdapter
												.getmEntities();
										for (ExamSubEntity examSubEntity : entities) {
											examSubEntity.paperId = mPaperEntity.id;
										}
										try {
											DbExamController controller = new DbExamController(
													CountDownExamDetailActivity.this);
											controller
													.saveOrUpdate(mPaperEntity);
											controller.saveOrUpdate(entities);
										} catch (Exception e) {
											e.printStackTrace();
										} finally {
											runOnUiThread(new Runnable() {
												public void run() {
													// Intent intent = new
													// Intent(
													// CountDownExamDetailActivity.this,
													// MainActivityV2.class);
													// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
													// startActivity(intent);
													sendBroadcast(new Intent(
															ExamHistoryListActivity.FRESH_HISTORY_DATA_ACTION));
													sendBroadcast(new Intent(
															ExamSearchActivity.FRESH_EXAMINE_NUM_ACTION));
													sendBroadcast(new Intent(
															FINISH_EXAMINE_ACTIVITY_ACTION));
													finish();
												}
											});
										}
									};
								}.start();
							}
						})
				.setNeutralButton(getString(R.string.feedback_exist_cancel),
						null).create();
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	private String getInputAnswerMsg() {
		String sInputAnswerMsg = "";
		List<ExamSubEntity> dataList = mAdapter.getmEntities();
		for (int i = 0; i < dataList.size(); i++) {
			ExamSubEntity entity = dataList.get(i);
			String sTmpMsg = String.valueOf(entity.id) + ":";
			// =====================
			// 单选1 多选2 判断3 填空4
			// =====================
			/**
			 * 单选
			 */
			if (entity.type.equals("1")) {
				if (entity.inputAnswer.equals("")) {
					sTmpMsg += "0";
				} else {
					sTmpMsg += entity.inputAnswer;
				}
				sTmpMsg += "-1";
			}
			/**
			 * 多选
			 */
			else if (entity.type.equals("2")) {
				if (entity.inputAnswerList == null
						|| entity.inputAnswerList.size() <= 0) {
					sTmpMsg += "0";
				} else {
					for (String sInputAnswer : entity.inputAnswerList) {
						if (sInputAnswer.equals("")) {
							sTmpMsg += "0" + ";";
						} else {
							sTmpMsg += sInputAnswer + ";";
						}
					}
				}
				sTmpMsg += "-2";
			}
			/**
			 * 判断
			 */
			else if (entity.type.equals("3")) {
				if (entity.inputAnswer.equals("")) {
					sTmpMsg += "0";
				} else {
					sTmpMsg += entity.inputAnswer;
				}
				sTmpMsg += "-3";
			}
			/**
			 * 排序
			 */
			else if (entity.type.equals("3")) {
				if (entity.inputAnswerList == null
						|| entity.inputAnswerList.size() <= 0) {
					sTmpMsg += "0";
				} else {
					for (String sInputAnswer : entity.inputAnswerList) {
						if (sInputAnswer.equals("")) {
							sTmpMsg += "0" + ";";
						} else {
							sTmpMsg += sInputAnswer + ";";
						}
					}
				}
				sTmpMsg += "-4";
			}
			sInputAnswerMsg += sTmpMsg + "_";
		}
		/**
		 * 截取最后1位的"_"
		 */
		if (sInputAnswerMsg.length() > 0) {
			sInputAnswerMsg = sInputAnswerMsg.substring(0,
					sInputAnswerMsg.length() - 1);
		}
		return sInputAnswerMsg;
	}
}
